package com.zhq.security.auth.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhq.system.entity.SysUser;
import com.zhq.system.mapper.SysUserMapper;
import com.zhq.system.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;

@Service
public class UserDetailServiceImpl implements UserDetailsService {

    private static final long serialVersionUID = -6743567631108323096L;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        SysUser sysUser=sysUserMapper.selectOne(new QueryWrapper<SysUser>().eq("user_name",s));
        if (sysUser==null){
            throw  new UsernameNotFoundException("用户不存在");
        }
        if(redisTemplate.opsForValue().get(serialVersionUID+s)!=null){
            throw  new BadCredentialsException("账户已被锁定");
        }


        return new User(s,sysUser.getLoginPwd(),new ArrayList<>());
    }
}
